const { delete: deleteProject, query, create, update } = require("../service/project.service");

class ProjectController {
  async getProjectList(ctx, next) {
    try {
      const { name, personId } = ctx.request.body;
      let params = null;
      if (name || personId) {
        params = {};
        name && (params.name = name);
        personId && (params.personId = personId);
      }
      const res = await query(params);
      ctx.success(res);
    } catch (err) {
      ctx.fail("查询项目列表失败！");
    }
  }
  async queryProjectById(ctx, next) {
    try {
      const { id } = ctx.params;
      const res = await query({ id });
      ctx.success(res[0]);
    } catch (err) {
      ctx.fail("查询项目项目详情失败！");
    }
  }
  async createProject(ctx, next) {
    try {
      const res = await create(ctx.request.body);
      if (res.affectedRows > 0) return ctx.success();
      ctx.fail("创建项目失败！");
    } catch (err) {
      ctx.fail("创建项目失败！");
    }
  }
  async updateProjectById(ctx, next) {
    let data = ctx.request.body;
    let params = [data, { id: data.id }];
    delete params[0].id;
    try {
      const res = await update(params);
      if (res.affectedRows > 0) return ctx.success();
      ctx.fail("更新项目失败!")
    } catch (err) {
      ctx.fail("更新项目失败!")
    }
  }
  async deleteProjectById(ctx, next) {
    let { id } = ctx.request.body;
    let params = { id };
    try {
      const res = await deleteProject(params);
      if (res.affectedRows > 0) return ctx.success();
      ctx.fail("删除项目失败!")
    } catch (err) {
      ctx.fail("删除项目失败!")
    }
  }
}

module.exports = new ProjectController();